import pymysql
from faker import Faker

if __name__ == '__main__':
    # 初始化Faker，生成中文数据
    faker = Faker(locale='zh_CN')

    # 连接数据库
    conn = pymysql.connections.Connection(
        host="127.0.0.1",
        port=3306,
        user="root",
        password="root",
        db="shop"
    )
    cursor = conn.cursor()

    # 插入100条记录（不包含age字段）
    for i in range(100):
        name = faker.name()
        email = faker.email()
        username = faker.user_name()
        password = faker.password()
        # 只插入表中实际存在的字段
        sql = "insert into user (username,password,name, email) values (%s, %s,%s, %s)"

        # 执行SQL
        result = cursor.execute(sql, (username,password,name, email))

        # 每插入10条数据打印一次进度
        if (i + 1) % 10 == 0:
            print(f"已插入 {i + 1} 条数据")

    # 提交事务
    conn.commit()
    print("100条数据插入完成")

    # 关闭连接
    cursor.close()
    conn.close()
